// 系统设置API接口
import { http, getAPI_BASE_URL_SYNC } from '../lib/http-client';
import { shouldUseMockServer } from '../config/app.config';

// 系统设置API基础路径
const SETTINGS_API_BASE = `${getAPI_BASE_URL_SYNC()}/settings`;

// API请求参数接口
export interface GetSettingsParams {
  type?: 'personal' | 'notification' | 'security' | 'system';
  userId?: number;
}

// API响应接口
export interface ApiResponse<T> {
  data: T;
  total: number;
  success: boolean;
  message?: string;
}

// 后端API响应格式（根据实际后端API调整）
interface BackendApiResponse<T> {
  code: number;
  message: string;
  data: T;
  total?: number;
  success?: boolean;
}

// 导入类型定义
import type { PersonalSettings, NotificationSettings, SecuritySettings, SystemConfigurations } from '../types/settings';

// 系统设置响应格式
interface SettingsResponse {
  personal: PersonalSettings;
  notification: NotificationSettings;
  security: SecuritySettings;
  system: SystemConfigurations;
}

// 模拟数据导入
import { settingsData as mockSettingsData } from '../data/settingsData';

// 模拟API实现
const mockSettingsApi = {
  async getSettings(params: GetSettingsParams = {}): Promise<ApiResponse<SettingsResponse>> {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const { type } = params;
    
    if (type) {
      const data = mockSettingsData[type];
      return {
        data: { [type]: data } as SettingsResponse,
        total: 1,
        success: true,
        message: '获取设置成功'
      };
    }
    
    return {
      data: mockSettingsData as SettingsResponse,
      total: 1,
      success: true,
      message: '获取所有设置成功'
    };
  },

  async updatePersonalSettings(settings: Partial<PersonalSettings>): Promise<ApiResponse<PersonalSettings>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    mockSettingsData.personal = { ...mockSettingsData.personal, ...settings };
    
    return {
      data: mockSettingsData.personal,
      total: 1,
      success: true,
      message: '个人设置更新成功'
    };
  },

  async updateNotificationSettings(settings: Partial<NotificationSettings>): Promise<ApiResponse<NotificationSettings>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    mockSettingsData.notification = { ...mockSettingsData.notification, ...settings };
    
    return {
      data: mockSettingsData.notification,
      total: 1,
      success: true,
      message: '通知设置更新成功'
    };
  },

  async updateSecuritySettings(settings: Partial<SecuritySettings>): Promise<ApiResponse<SecuritySettings>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    mockSettingsData.security = { ...mockSettingsData.security, ...settings };
    
    return {
      data: mockSettingsData.security,
      total: 1,
      success: true,
      message: '安全设置更新成功'
    };
  },

  async updateSystemConfigurations(config: Partial<SystemConfigurations>): Promise<ApiResponse<SystemConfigurations>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    mockSettingsData.system = { ...mockSettingsData.system, ...config };
    
    return {
      data: mockSettingsData.system,
      total: 1,
      success: true,
      message: '系统配置更新成功'
    };
  },

  async changePassword(passwordData: {
    currentPassword: string;
    newPassword: string;
    confirmPassword: string;
  }): Promise<ApiResponse<boolean>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    if (passwordData.newPassword !== passwordData.confirmPassword) {
      return {
        data: false,
        total: 1,
        success: false,
        message: '新密码和确认密码不匹配'
      };
    }
    
    return {
      data: true,
      total: 1,
      success: true,
      message: '密码修改成功'
    };
  },

  async resetSettings(type: 'personal' | 'notification' | 'security' | 'system' | 'all'): Promise<ApiResponse<boolean>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    // 重置为默认值
    const defaultData = {
      personal: {
        id: '1',
        name: '赵工程师',
        email: 'zhao@example.com',
        phone: '138****6789',
        language: '中文',
        timeZone: 'GMT+8',
        department: '技术部',
        position: '高级工程师'
      },
      notification: {
        id: '1',
        email: {
          newTask: true,
          taskUpdate: true,
          comment: true,
          system: true
        },
        push: {
          newTask: true,
          taskUpdate: false,
          comment: true,
          system: false
        },
        sms: {
          newTask: false,
          taskUpdate: false,
          comment: false,
          emergency: true
        },
        audio: {
          enabled: true,
          volume: 80,
          voicePrompt: true,
          newMessage: true,
          taskNotification: true,
          systemNotification: true
        },
        dailySummary: "afternoon",
        weeklySummary: "none"
      },
      security: {
        id: '1',
        twoFactorAuth: true,
        loginAlerts: true,
        sessionTimeout: 30,
        passwordExpiry: 90,
        failedLoginAttempts: 5,
        ipWhitelist: ['192.168.1.0/24', '10.0.0.0/8']
      },
      system: {
        id: '1',
        language: '中文',
        timeZone: 'GMT+8',
        theme: 'light',
        autoSave: true,
        backupInterval: 24,
        maxFileSize: 10,
        allowedFileTypes: ['jpg', 'png', 'pdf', 'doc', 'docx']
      }
    };
    
    if (type === 'all') {
      Object.assign(mockSettingsData, defaultData);
    } else {
      mockSettingsData[type] = defaultData[type];
    }
    
    return {
      data: true,
      total: 1,
      success: true,
      message: `${type}设置重置成功`
    };
  }
};

export const settingsApi = {
  // 获取系统设置（支持按类型筛选）
  async getSettings(params: GetSettingsParams = {}): Promise<ApiResponse<SettingsResponse>> {
    if (shouldUseMockServer()) {
      return mockSettingsApi.getSettings(params);
    }
    
    try {
      const { type, userId } = params;
      
      // 构建查询参数
      const queryParams = new URLSearchParams();
      
      if (type) queryParams.append('type', type);
      if (userId) queryParams.append('userId', userId.toString());
      
      const url = `${SETTINGS_API_BASE}${queryParams.toString() ? `?${queryParams.toString()}` : ''}`;
      
      // 发送GET请求
      const response = await http.get<BackendApiResponse<SettingsResponse>>(url);
      
      // 根据后端API响应格式调整
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '获取系统设置成功'
        };
      } else {
        throw new Error(backendData.message || '获取系统设置失败');
      }
    } catch (error) {
      console.error('获取系统设置失败:', error);
      
      // 如果后端API不可用，返回默认数据（开发阶段）
      return {
        data: {
          personal: {
            name: '赵工程师',
            email: 'zhao@example.com',
            phone: '138****6789',
            department: '技术部',
            position: '高级工程师',
            securityQuestion: '您母亲的姓名是？',
            securityAnswer: ''
          },
          notification: {
            email: {
              newTask: true,
              taskUpdate: true,
              comment: true,
              system: true
            },
            push: {
              newTask: true,
              taskUpdate: false,
              comment: true,
              system: false
            },
            sms: {
              newTask: false,
              taskUpdate: false,
              comment: false,
              emergency: true
            },
            audio: {
              enabled: true,
              volume: 80,
              voicePrompt: true,
              newMessage: true,
              taskNotification: true,
              systemNotification: true
            },
            dailySummary: "afternoon",
            weeklySummary: "none"
          },
          security: {
            twoFactorEnabled: true,
            passwordExpires: '3个月',
            passwordExpiry: "3",
            lastPasswordChange: '2023-01-15',
            sessionTimeout: "30",
            allowedIPs: ['192.168.1.0/24', '10.0.0.0/8'],
            loginHistory: [
              { time: '2023-03-03 09:30', location: '北京', device: 'Chrome / Windows' },
              { time: '2023-03-02 16:45', location: '北京', device: 'Safari / MacOS' },
              { time: '2023-03-01 11:20', location: '上海', device: 'Firefox / Windows' },
              { time: '2023-02-28 15:10', location: '北京', device: 'Edge / Windows' }
            ]
          },
          system: {
            language: '中文',
            timeZone: 'GMT+8',
            dateFormat: 'YYYY-MM-DD',
            timeFormat: '24小时制',
            defaultProject: '电商系统项目群',
            dashboardLayout: '标准视图',
            theme: 'light'
          }
        },
        total: 1,
        success: false,
        message: error instanceof Error ? error.message : '获取系统设置失败'
      };
    }
  },

  // 更新个人设置
  async updatePersonalSettings(settings: Partial<PersonalSettings>): Promise<ApiResponse<PersonalSettings>> {
    if (shouldUseMockServer()) {
      return mockSettingsApi.updatePersonalSettings(settings);
    }
    
    try {
      const url = `${SETTINGS_API_BASE}/personal`;
      
      // 发送PUT请求
      const response = await http.put<BackendApiResponse<PersonalSettings>>(url, settings);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '个人设置更新成功'
        };
      } else {
        throw new Error(backendData.message || '更新个人设置失败');
      }
    } catch (error) {
      console.error('更新个人设置失败:', error);
      throw new Error(error instanceof Error ? error.message : '更新个人设置失败');
    }
  },

  // 更新通知设置
  async updateNotificationSettings(settings: Partial<NotificationSettings>): Promise<ApiResponse<NotificationSettings>> {
    if (shouldUseMockServer()) {
      return mockSettingsApi.updateNotificationSettings(settings);
    }
    
    try {
      const url = `${SETTINGS_API_BASE}/notification`;
      
      // 发送PUT请求
      const response = await http.put<BackendApiResponse<NotificationSettings>>(url, settings);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '通知设置更新成功'
        };
      } else {
        throw new Error(backendData.message || '更新通知设置失败');
      }
    } catch (error) {
      console.error('更新通知设置失败:', error);
      throw new Error(error instanceof Error ? error.message : '更新通知设置失败');
    }
  },

  // 更新安全设置
  async updateSecuritySettings(settings: Partial<SecuritySettings>): Promise<ApiResponse<SecuritySettings>> {
    if (shouldUseMockServer()) {
      return mockSettingsApi.updateSecuritySettings(settings);
    }
    
    try {
      const url = `${SETTINGS_API_BASE}/security`;
      
      // 发送PUT请求
      const response = await http.put<BackendApiResponse<SecuritySettings>>(url, settings);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '安全设置更新成功'
        };
      } else {
        throw new Error(backendData.message || '更新安全设置失败');
      }
    } catch (error) {
      console.error('更新安全设置失败:', error);
      throw new Error(error instanceof Error ? error.message : '更新安全设置失败');
    }
  },

  // 更新系统配置
  async updateSystemConfigurations(config: Partial<SystemConfigurations>): Promise<ApiResponse<SystemConfigurations>> {
    if (shouldUseMockServer()) {
      return mockSettingsApi.updateSystemConfigurations(config);
    }
    
    try {
      const url = `${SETTINGS_API_BASE}/system`;
      
      // 发送PUT请求
      const response = await http.put<BackendApiResponse<SystemConfigurations>>(url, config);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '系统配置更新成功'
        };
      } else {
        throw new Error(backendData.message || '更新系统配置失败');
      }
    } catch (error) {
      console.error('更新系统配置失败:', error);
      throw new Error(error instanceof Error ? error.message : '更新系统配置失败');
    }
  },

  // 修改密码
  async changePassword(passwordData: {
    currentPassword: string;
    newPassword: string;
    confirmPassword: string;
  }): Promise<ApiResponse<boolean>> {
    if (shouldUseMockServer()) {
      return mockSettingsApi.changePassword(passwordData);
    }
    
    try {
      const url = `${SETTINGS_API_BASE}/password`;
      
      // 发送POST请求
      const response = await http.post<BackendApiResponse<boolean>>(url, passwordData);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: true,
          total: 1,
          success: true,
          message: backendData.message || '密码修改成功'
        };
      } else {
        throw new Error(backendData.message || '修改密码失败');
      }
    } catch (error) {
      console.error('修改密码失败:', error);
      throw new Error(error instanceof Error ? error.message : '修改密码失败');
    }
  },

  // 重置设置到默认值
  async resetSettings(type: 'personal' | 'notification' | 'security' | 'system' | 'all'): Promise<ApiResponse<boolean>> {
    if (shouldUseMockServer()) {
      return mockSettingsApi.resetSettings(type);
    }
    
    try {
      const url = `${SETTINGS_API_BASE}/reset`;
      
      // 发送POST请求
      const response = await http.post<BackendApiResponse<boolean>>(url, { type });
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: true,
          total: 1,
          success: true,
          message: backendData.message || '设置重置成功'
        };
      } else {
        throw new Error(backendData.message || '重置设置失败');
      }
    } catch (error) {
      console.error('重置设置失败:', error);
      throw new Error(error instanceof Error ? error.message : '重置设置失败');
    }
  }
};